package com.cff.springbootwork.ldap.service;

import java.io.UnsupportedEncodingException;

import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.ldap.LdapName;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.ldap.support.LdapNameBuilder;
import org.springframework.stereotype.Service;

import com.cff.springbootwork.ldap.domain.Person;

@Service
public class LdapService {
	@Autowired
	private LdapTemplate ldapTemplate;

	public String addUser(String userName, String passwd) {
		LdapNameBuilder ldapNameBuilder = LdapNameBuilder.newInstance();
		ldapNameBuilder.add("cn", userName);
		LdapName build = ldapNameBuilder.build();

		BasicAttribute ocattr = new BasicAttribute("objectClass");
		ocattr.add("person");
		// 用户属性
		Attributes attrs = new BasicAttributes();
		attrs.put(ocattr);
		attrs.put("cn", userName);
		attrs.put("name", userName);
		attrs.put("userPassword", passwd);
		ldapTemplate.bind(build, null, attrs);

		return "0000";
	}

	public String removeUser(String userName) {
		LdapNameBuilder ldapNameBuilder = LdapNameBuilder.newInstance();
		ldapNameBuilder.add("cn", userName);
		LdapName build = ldapNameBuilder.build();
		ldapTemplate.unbind(build);
		return "0000";
	}

	public Person findByUsername(String username, String password) throws NamingException {
		AndFilter filter = new AndFilter();
		filter.and(new EqualsFilter("objectClass", "person"));
		filter.and(new EqualsFilter("cn", username));

		LdapNameBuilder ldapNameBuilder = LdapNameBuilder.newInstance();
		ldapNameBuilder.add("cn", username);
		LdapName build = ldapNameBuilder.build();

		Person person = ldapTemplate.search(build, filter.encode(), new AttributesMapper<Person>() {
			@Override
			public Person mapFromAttributes(Attributes attributes) throws NamingException {
				Person person = new Person();
				person.setUserName(attributes.get("cn").get().toString());
				person.setName(attributes.get("name").get().toString());
				return person;
			}
		}).get(0);
		return person;
	}

	public LdapTemplate getLdapTemplate() {
		return ldapTemplate;
	}

	public void setLdapTemplate(LdapTemplate ldapTemplate) {
		this.ldapTemplate = ldapTemplate;
	}

}